package com.ysd.lis.service.lab.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.HisReqDto;
import com.ysd.lis.request.PrintBarcodeDto;
import com.ysd.lis.request.SysParamFieldValueDto;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.impl.SysRuleSetServiceImpl;
import com.ysd.lis.service.lab.*;
import com.ysd.lis.util.InterfaceUtil;
import com.ysd.util.AgeUtils;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 申请中间表 服务实现类
 * </p>
 *
 * @author HuaiXing
 * @since 2024-01-18
 */
@Service
public class LabHisReqServiceImpl extends ServiceImpl<LabHisReqMapper, LabHisReq> implements LabHisReqService {

    private static final Logger logger = LoggerFactory.getLogger(LabHisReqServiceImpl.class);

    @Autowired
    LabBarCodeTypeMapper labBarCodeTypeMapper;
    @Autowired
    LabFeeItemMapper labFeeItemMapper;
    @Autowired
    LabFeeitemVsBarcodeMapper labFeeitemVsBarcodeMapper;
    @Autowired
    LabReqMainService labReqMainService;
    @Autowired
    LabReqdetailService labReqdetailService;
    @Autowired
    LabReqPrintMapper labReqPrintMapper;
    @Autowired
    LabReqPrintService labReqPrintService;
    @Autowired
    LabHisReqMapper labHisReqMapper;
    @Autowired
    SysBasDictDetailService dictDetailService;
    @Autowired
    LabReqStateMapper labReqStateMapper;
    @Autowired
    LabReqStateService labReqStateService;
    @Autowired
    SysRuleSetServiceImpl sysRuleSetService;
    @Autowired
    SysParamValueService sysParamValueService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    InterfaceUtil interfaceUtil;
    @Autowired
    LabProcessSetMapper processSetMapper;

    @Autowired
    RedisSysParamHelper redisSysParamHelper;

    //条码打印
    @Transactional//开启事务
    @Override
    public Result printBarcode(HisReqDto dto) {

        List<LabHisReq> labHisReqList = dto.getLabHisReqList();

        //根据病历号和项目排序
        List<LabHisReq> collect = labHisReqList.stream().sorted(Comparator.comparing(LabHisReq::getPatNo, Comparator.reverseOrder()).thenComparing(LabHisReq::getFeeCode, Comparator.reverseOrder())).collect(Collectors.toList());

        List<LabReqMain> labReqMainList = new ArrayList<>();
        List<LabReqdetail> labReqDetailList = new ArrayList<>();
        List<LabReqPrint> labReqPrintList = new ArrayList<>();

        //TODO 此处从配置里取，根据配置判断用his条码还是自己生成条码
        boolean useMainIdSqh = false;

        SysUser sysUser = RedisUserManager.getUser();

        String reqNo = null, oldPatNo = null, oldBarcodeType = null, oldFeeCode = null, oldMainId = null;
        //循环判断是否需要分管

        for (LabHisReq labHisReq : collect) {
            LambdaQueryWrapper<LabReqPrint> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabReqPrint::getDelFlag, 0).eq(LabReqPrint::getHisReqId, labHisReq.getApplicantId());
            Integer count = labReqPrintMapper.selectCount(lambdaQueryWrapper);
            if (count > 0) {
                //当前申请已经打印过
                continue;
            }
            LabReqMain labReqMain = new LabReqMain();
            LabReqdetail labReqdetail = new LabReqdetail();
            LabReqPrint labReqPrint = new LabReqPrint();
            //是否分管标识
            boolean newReq = false;
            //判断是否是同一病人，如果不是则分管
            String patNo = labHisReq.getPatNo();
            if (!Objects.equals(oldPatNo, patNo)) {
                newReq = true;
            }
            oldPatNo = patNo;

            if (useMainIdSqh) {
                String mainId = labHisReq.getMainId();
                if (!Objects.equals(mainId, oldMainId)) {
                    newReq = true;
                }
                oldMainId = mainId;
            } else {
                //判断分管类别，如果不是同一类别则分管
                String feeCode = labHisReq.getFeeCode();
                LambdaQueryWrapper<LabFeeItem> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(LabFeeItem::getDelFlag, 0).eq(LabFeeItem::getFeeCode, feeCode);
                LabFeeItem labFeeItem = labFeeItemMapper.selectOne(wrapper);
                LambdaQueryWrapper<LabFeeitemVsBarcode> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(LabFeeitemVsBarcode::getDelFlag, 0)
                //.eq(LabFeeitemVsBarcode::getFeeId, labFeeItem.getId())
                ;
                LabFeeitemVsBarcode labFeeitemVsBarcode = labFeeitemVsBarcodeMapper.selectOne(queryWrapper);
//                String barcodeId = labFeeitemVsBarcode.getBarcodeId();
//                if (!Objects.equals(barcodeId, oldBarcodeType)) {
//                    newReq = true;
//                }
//                oldBarcodeType = barcodeId;
//
//                //申请项目相同
//                if (Objects.equals(feeCode, oldFeeCode)) {
//                    newReq = true;
//                }
                oldFeeCode = feeCode;
            }

            //判断是否分管
            if (newReq) {
                BeanUtil.copyProperties(labHisReq, labReqMain, "id");
                labReqMain.setPrinterNa(sysUser.getRealname());
                labReqMain.setPrintDoctor(sysUser.getUsername());
                Date now = new Date();
                Timestamp ts = new Timestamp(now.getTime());
                labReqMain.setPrintTime(ts);
                if (useMainIdSqh) {
                    //直接使用his条码
                    reqNo = labHisReq.getMainId();
                    labReqMain.setReqNo(reqNo);
                } else {
                    //TODO 条码生成规则，先写死在这，后期在做！
                    SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
                    String format = f.format(now);
                    reqNo = format + "000";
                    labReqMain.setReqNo(reqNo);
                }
                labReqMainList.add(labReqMain);
            }
            //保存明细信息
            BeanUtil.copyProperties(labHisReq, labReqdetail, "id");
            labReqdetail.setReqNo(reqNo);
            labReqdetail.setHisUnique(labHisReq.getApplicantId());
            labReqdetail.setHisAdvNo(labHisReq.getAdviceId());
            labReqDetailList.add(labReqdetail);
            //保存打印记录信息
            labReqPrint.setHisReqId(labHisReq.getApplicantId());
            labReqPrintList.add(labReqPrint);
        }

        //保存数据到数据库
        boolean b = labReqMainService.saveBatch(labReqMainList);
        if (!b) {
            return Result.fail("插入申请主信息报错");
        }
        boolean b1 = labReqdetailService.saveBatch(labReqDetailList);
        if (!b1) {
            return Result.fail("插入申请明细信息报错");
        }
        boolean b2 = labReqPrintService.saveBatch(labReqPrintList);
        if (!b2) {
            return Result.fail("插入打印记录信息报错");
        }
        return Result.succ(1, "成功", "");
    }


    //查询
    @Override
    public synchronized Result barcodePrintSearch(PrintBarcodeDto dto) {
        logger.info("条码查询入参为：" + JSONUtil.toJsonStr(dto));
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader("Authorization").replace("Bearer ", "");
            String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);
            dto.setOrgId(orgId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //进行数据处理
        if (CollectionUtils.isNotEmpty(dto.getDeptNo())) {
            dto.setDeptNos(String.join(",", dto.getDeptNo()));
        }
        if (CollectionUtils.isNotEmpty(dto.getPatType())) {
            dto.setPatTypes(String.join(",", dto.getPatType()));
        }
        /*先调接口拉取数据*/
        LambdaQueryWrapper<SysInterface> interwrapper = new LambdaQueryWrapper<>();
        interwrapper.eq(SysInterface::getDelFlag, 0);
        interwrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(interwrapper);
        List<String> collect2 = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        try {
            if (CollectionUtils.isNotEmpty(collect2)) {
                for (String webUrl : collect2) {
                    logger.info("调用接口" + webUrl);
                    String returnMsg = HttpUtil.createPost(webUrl + "/public/SyncReqMainMany").body(JSONUtil.toJsonStr(dto)).contentType("application/json").execute().body();
                    logger.info("调用接口返回" + returnMsg);
                    JSONObject jsonObject = new JSONObject(returnMsg);
                    JSONObject status = jsonObject.getJSONObject("status");
                    String code = status.get("code").toString();
                    String msg = status.get("msg").toString();
                    logger.info("调用接口返回:" + code + "^" + msg);
                    if ("400".equals(code)) {
                        return Result.fail("接口管理平台异常,请检查");
                    }
                    //调用公卫平台接口获取申请信息
                    logger.info("开始调用公卫系统接口获取打印条码信息");
                    String body = HttpUtil.createPost(webUrl + "/public/SyncGwReqMainMany").body(JSONUtil.toJsonStr(dto)).contentType("application/json").execute().body();
                    logger.info("调用公卫系统接口返回" + body);
                }
            } else {
                //return Result.fail("接口管理平台异常,请检查");
            }
        } catch (Exception e) {
            //throw new RuntimeException("接口管理平台异常,请检查");
        }

        MPJLambdaWrapper<LabHisReq> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabHisReq.class).eq(LabHisReq::getDelFlag, 0);
        queryWrapper.selectAs("smpt", LabSampleType::getSampleTypeName, LabHisReq::getSampleTypeNa);
        queryWrapper.selectAs("dept", SysOrgDepartment::getName, LabHisReq::getReqDeptNa);
        queryWrapper.selectAs("reqDoc", PubEmployee::getName, LabHisReq::getReqDoctorNa);
        queryWrapper.selectAs("sampDoc", PubEmployee::getName, LabHisReq::getSamplingDoctorNa);

        queryWrapper.selectAs("vsid", LabFeeitemVsBarcode::getId, LabHisReq::getFeeVsBarcodeId);
        queryWrapper.selectAs("barcode", LabBarCodeType::getBarcodeNo, LabHisReq::getBarCodeNo);

        //LambdaQueryWrapper<LabHisReq> queryWrapper = new LambdaQueryWrapper<>();
        //queryWrapper.eq(LabHisReq::getDelFlag, 0);

        String patNo = dto.getPatNo();
        if (!StringUtils.isEmpty(patNo)) {
            queryWrapper.eq(LabHisReq::getPatNo, patNo);
        }

        if (!StringUtils.isEmpty(dto.getEwmNo())) {
            queryWrapper.and(wrapper ->
                    wrapper.eq(LabHisReq::getPatNo, dto.getEwmNo())
                            .or()
                            .eq(LabHisReq::getIdNo, dto.getEwmNo()));
        }

        String reqNo;
        if (dto.getFilterotherDept() != null && dto.getFilterotherDept() != 1) {
            reqNo = dto.getReqNo();
            if (!StringUtils.isEmpty(reqNo)) {
                queryWrapper.eq(LabHisReq::getMainId, reqNo);
            }
            String bedNo = dto.getBedNo();
            if (!StringUtils.isEmpty(bedNo)) {
                queryWrapper.eq(LabHisReq::getBedNo, bedNo);
            }
            //String patType = dto.getPatType();
            if (ToolsUtils.isNotEmpty(dto.getPatType()) && dto.getPatType().size() > 0) {
                queryWrapper.in(LabHisReq::getPatType, dto.getPatType());
            }
            List<String> deptList = dto.getDeptNo();
            if (deptList.size() > 0) {
                //queryWrapper.in(LabHisReq::getReqDept, deptList);
                queryWrapper.and(p -> p.in(LabHisReq::getReqDept, deptList).or().in(LabHisReq::getReqWard, deptList));
            }

            String patNa = dto.getPatNa();
            if (!StringUtils.isEmpty(patNa)) {
                queryWrapper.eq(LabHisReq::getPatNa, patNa);
            }

            String idNo = dto.getIDNo();
            if (!StringUtils.isEmpty(idNo)) {
                queryWrapper.eq(LabHisReq::getIdNo, idNo);
            }

        }
        // queryWrapper
        //         .ge(LabHisReq::getReqTime, dto.getReqDateS())
        //         .le(LabHisReq::getReqTime, dto.getReqDateE());
        queryWrapper.between(LabHisReq::getReqTime, dto.getReqDateS(), dto.getReqDateE());

        //StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_REQ_PRINT p WHERE t.ID = p.HIS_REQ_ID ");
        //queryWrapper.notExists(existsSql.toString());
        queryWrapper.isNull(LabHisReq::getReqNo);
        queryWrapper.leftJoin(LabSampleType.class, "smpt", p -> p.eq(LabSampleType::getSampleTypeCode, LabHisReq::getSampleType).eq(LabSampleType::getDelFlag, 0).eq(LabSampleType::getOrgId, LabHisReq::getOrgId).isNotNull(LabSampleType::getSampleTypeCode));
        queryWrapper.leftJoin(SysOrgDepartment.class, "dept", p -> p.eq(SysOrgDepartment::getCode, LabHisReq::getReqDept).eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, LabHisReq::getOrgId).isNotNull(SysOrgDepartment::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "reqDoc", p -> p.eq(PubEmployee::getCode, LabHisReq::getReqDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabHisReq::getOrgId).isNotNull(PubEmployee::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "sampDoc", p -> p.eq(PubEmployee::getCode, LabHisReq::getSamplingDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabHisReq::getOrgId).isNotNull(PubEmployee::getCode));
        queryWrapper.leftJoin(LabFeeitemVsBarcode.class, "vsid", p -> p.eq(LabFeeitemVsBarcode::getFeeCode, LabHisReq::getFeeCode).eq(LabFeeitemVsBarcode::getDelFlag, 0).eq(LabFeeitemVsBarcode::getOrgId, LabHisReq::getOrgId).isNotNull(LabFeeitemVsBarcode::getBarcodeNo));
        queryWrapper.leftJoin(LabBarCodeType.class, "barcode", p -> p.eq(LabBarCodeType::getBarcodeNo, LabFeeitemVsBarcode::getBarcodeNo).eq(LabBarCodeType::getDelFlag, 0).eq(LabBarCodeType::getOrgId, LabHisReq::getOrgId).isNotNull(LabBarCodeType::getBarcodeNo));
        List<LabHisReq> labHisReqList = labHisReqMapper.selectList(queryWrapper);


        //labHisReqList 过滤掉feeCode和patNo和adviceId 相同的数据,20241220  山亭会议  副总要求把  医嘱Id  改为 申请时间

        // 使用 Stream API 进行过滤
        labHisReqList = labHisReqList.stream()
                .collect(Collectors.groupingBy(labHisReq ->
                        labHisReq.getPatNo() + "-" + labHisReq.getFeeCode() + "-" + labHisReq.getReqTime()))
                .values().stream()
                .map(list -> list.get(0)) // 只保留每个分组的第一个元素
                .collect(Collectors.toList());


        // Map<String, LabHisReq> map = labHisReqList.stream()
        //         .collect(Collectors.toMap(LabHisReq::getFeeCode, labHisReq -> labHisReq, (labHisReq1, labHisReq2) -> {
        //             labHisReq2.setReqNo(labHisReq1.getReqNo() + "-" + labHisReq2.getReqNo());
        //             return labHisReq2;
        //         }));
        // labHisReqList = new ArrayList<>(map.values());


        logger.info("查询labHisReq结果数量为：" + labHisReqList.size());
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();

        for (LabHisReq maininfo : labHisReqList) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
        }

        logger.info("根据病历号和项目排序");
        //根据病历号和项目排序
        List<LabHisReq> collect = labHisReqList.stream().sorted(Comparator.comparing(LabHisReq::getBedNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabHisReq::getPatNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabHisReq::getPatId, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabHisReq::getBarCodeNo, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabHisReq::getIsUrgent, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabHisReq::getSampleType, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabHisReq::getGroupCode, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(LabHisReq::getFeeCode, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());


        reqNo = null;
        String oldPatNo = null, oldBarcodeType = null, oldFeeCode = null, oldMainId = null, color = null;

        //TODO 此处从配置里取，根据配置判断用his条码还是自己生成条码

        boolean useMainIdSqh = false;//使用HIS申请号（条码号）

        try {
            /*条码打印方式
             * 1、LIS 打印条码
             * 2、HIS打印条码
             * 3、启用本地参数中配置
             * 没有配置  默认采用LIS  打印条码处理
             * */
            SysParamParam sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("tmdyfs");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if (r1.get(0).getValue().equals("2")) {
                    useMainIdSqh = true;
                }

                if (r1.get(0).getValue().equals("3")) {
                    if (StringUtils.isNotEmpty(dto.getLocalPcName())) {
                        sysp1 = new SysParamParam();
                        sysp1.setParamCode("bdxtcs");
                        sysp1.setField("bdtmdyfs");
                        sysp1.setLocalComputer(dto.getLocalPcName());
                        List<SysParamFieldValueDto> r2 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                        if (!r2.isEmpty()) {
                            if (r2.get(0).getValue().equals("2")) {
                                useMainIdSqh = true;
                            }
                        }
                    }
                    //参数中本地计算机名称为空按采用LIS 打印条码处理
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //TODO
        }

        logger.info("开始分管");
        if (useMainIdSqh) {
            logger.info("开始分管useMainIdSqh");
            List<LabHisReq> collect1 = labHisReqList.stream().sorted(Comparator.comparing(LabHisReq::getMainId, Comparator.reverseOrder())).collect(Collectors.toList());
            for (LabHisReq labHisReq : collect1) {
                String mainId = labHisReq.getMainId();
                if (!Objects.equals(mainId, oldMainId)) {
                    //生成随机的颜色值,同一条码颜色一样
                    StringBuffer result = new StringBuffer();
                    for (int i = 0; i < 6; i++) {
                        //随机生成0-15的数值并转换成16进制
                        result.append(Integer.toHexString(new Random().nextInt(16)));
                    }
                    color = "#" + result.toString().toUpperCase();
                }
                oldMainId = mainId;
                labHisReq.setReqNo(mainId);
                labHisReq.setSameSpecCodeBgColor(color);
            }
            logger.info("查询成功!处理结束");
            return Result.succ(1, "查询成功!", collect1);
        } else {
            logger.info("循环判断是否需要分管");
            //循环判断是否需要分管
            String feecodeStr = collect.isEmpty() ? "!@#QWE" : collect.stream().map(LabHisReq::getFeeCode).distinct().collect(Collectors.joining("','"));
            LambdaQueryWrapper<LabFeeItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LabFeeItem::getDelFlag, 0);
            wrapper.inSql(LabFeeItem::getFeeCode, "select FEE_CODE from LAB_FEE_ITEM where FEE_CODE in ('" + feecodeStr + "')");
            //.eq(LabFeeItem::getFeeCode, feeCode);
            List<LabFeeItem> labFeeItems = labFeeItemMapper.selectList(wrapper);

            LambdaQueryWrapper<LabFeeitemVsBarcode> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(LabFeeitemVsBarcode::getDelFlag, 0);
            //queryWrapper1.eq(LabFeeitemVsBarcode::getFeeCode, labFeeItem.getFeeCode());
            queryWrapper1.inSql(LabFeeitemVsBarcode::getFeeCode, "select FEE_CODE from LAB_FEE_ITEM where FEE_CODE in ('" + feecodeStr + "')");
            List<LabFeeitemVsBarcode> labFeeitemVsBarcodes = labFeeitemVsBarcodeMapper.selectList(queryWrapper1);

//            List<LabHisReq> failList = new ArrayList<>();
            logger.info("开始循环");
            for (LabHisReq labHisReq : collect) {
                //是否分管标识
                boolean newReq = false;
                //判断是否是同一病人，如果不是则分管
                patNo = labHisReq.getPatNo();
                if (!Objects.equals(oldPatNo, patNo)) {
                    newReq = true;
                }
                oldPatNo = patNo;

                //判断分管类别，如果不是同一类别则分管
                String feeCode = labHisReq.getFeeCode();
                LabFeeItem labFeeItem = null;

                try {
                    List<LabFeeItem> list = labFeeItems.isEmpty() ? null : labFeeItems.stream().filter(p -> p.getFeeCode().equals(feeCode)).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(list)) {
                        labFeeItem = list.get(0);
                    }
                    //labFeeItem = labFeeItems.isEmpty() ? null : labFeeItems.stream().filter(p -> p.getFeeCode().equals(feeCode)).collect(Collectors.toList()).get(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                LabFeeitemVsBarcode labFeeitemVsBarcode = new LabFeeitemVsBarcode();
                if (BeanUtil.isEmpty(labFeeItem)) {
                    labHisReq.setCatchMessage("查无申请项目");
//                    failList.add(labHisReq);
                    continue;
                } else {
                    List<LabFeeitemVsBarcode> aimLts = labFeeitemVsBarcodes.stream().filter(p -> p.getFeeCode().equals(feeCode)).collect(Collectors.toList());
                    labFeeitemVsBarcode = labFeeitemVsBarcodes.isEmpty() ? null : aimLts.isEmpty() ? null : aimLts.get(0);
                }
                String barcodeId = BeanUtil.isEmpty(labFeeitemVsBarcode) || StringUtils.isEmpty(labFeeitemVsBarcode.getBarcodeNo()) ? "" : labFeeitemVsBarcode.getBarcodeNo();
                if (StringUtils.isEmpty(barcodeId)) {
                    String catchMessage = labHisReq.getCatchMessage();
                    if (catchMessage == null) {
                        catchMessage = "";
                    }
                    labHisReq.setCatchMessage(catchMessage + "," + "申请项目分管类型无对照");
//                    failList.add(labHisReq);
                    continue;
                }
                if (!Objects.equals(barcodeId, oldBarcodeType)) {
                    newReq = true;
                }
                oldBarcodeType = barcodeId;

                //申请项目相同
                if (Objects.equals(feeCode, oldFeeCode)) {
                    newReq = true;
                }
                oldFeeCode = feeCode;
                logger.info("判断是否分管");
                //判断是否分管
                if (newReq) {
                    // Date now = new Date();
                    // Timestamp ts = new Timestamp(now.getTime());
                    // //TODO 条码生成规则，先写死在这，后期在做！
                    // SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
                    // String format = f.format(now);
                    // int a = (int) (Math.random() * 900 + 100);
                    // String myStr = Integer.toString(a);
                    // reqNo = format + myStr;

                    List<String> list = sysRuleSetService.createRuleCodeList("reqNo", 1);

                    reqNo = list.get(0);
                    System.out.println("reqno:" + reqNo);

                    //生成随机的颜色值,同一条码颜色一样
                    StringBuffer result = new StringBuffer();
                    for (int i = 0; i < 6; i++) {
                        //随机生成0-15的数值并转换成16进制
                        result.append(Integer.toHexString(new Random().nextInt(16)));
                    }
                    color = "#" + result.toString().toUpperCase();
                }
                System.out.print("color" + color);
                labHisReq.setReqNo(reqNo);
                labHisReq.setSameSpecCodeBgColor(color);
            }
            logger.info("处理结束");
            //解决没有对照，数据重复问题，跟其他的业务无关，阿兴的bug
//            labHisReqList.addAll(failList);

            //labHisReqList 先根据reqNo排序然后再根据catchMessage排序,catchMessage为空的在前面
            //labHisReqList.sort(Comparator.comparing(LabHisReq::getReqNo, Comparator.reverseOrder()).thenComparing(LabHisReq::getCatchMessage));

            collect.sort(Comparator.comparing(LabHisReq::getReqNo, Comparator.nullsLast(Comparator.naturalOrder()))
                    .thenComparing((LabHisReq req) -> req.getCatchMessage() == null || req.getCatchMessage().isEmpty(), Comparator.reverseOrder()));

            return Result.succ(1, "成功", collect);
        }
    }


    //条码打印
    @Override
    public Result barcodePrint(HisReqDto dto) throws JsonProcessingException {

        List<LabHisReq> labHisReqList = dto.getLabHisReqList();
        //根据条码号排序
        List<LabHisReq> collect = labHisReqList.stream().sorted(Comparator.comparing(LabHisReq::getReqNo, Comparator.reverseOrder())).collect(Collectors.toList());

        List<LabReqMain> labReqMainList = new ArrayList<>();
        List<LabReqdetail> labReqDetailList = new ArrayList<>();
        List<LabReqPrint> labReqPrintList = new ArrayList<>();
        List<LabReqState> labReqStateList = new ArrayList<>();

        SysUser sysUser = new SysUser();

        try {
            sysUser = RedisUserManager.getUser();
        } catch (Exception e) {
            //接口传不过来先写死,慎重修改，银丰蔡总要求
            logger.info("获取缓存人员信息异常");
            sysUser.setOrgId("1787488360349155329");
            sysUser.setUsername("admin");
        }

        String reqNo, oldReqNo = null;
        //循环判断是否需要分管
        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "30");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        String value = "";
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }
        if (StringUtils.isEmpty(value)) {
            return Result.fail("未获取到词典状态信息----请检查系统设置中是否配置检验状态");
        }

        //收集所有的fee_code
        List<String> feeCodeList = collect.stream().map(LabHisReq::getFeeCode).distinct().collect(Collectors.toList());

        //通过fee_code查询所有的申请项目
        List<LabFeeItem> labFeeItems = labFeeItemMapper.selectList(new LambdaQueryWrapper<LabFeeItem>().in(LabFeeItem::getFeeCode, feeCodeList).eq(LabFeeItem::getDelFlag, 0));


        for (LabHisReq labHisReq : collect) {
            //取出和labHisReq patNo,feeCode,adviceId相同的数据并写入条码号

            String sex = null;
            LabReqMain labReqMain = new LabReqMain();
            LabReqdetail labReqdetail = new LabReqdetail();
            LabReqPrint labReqPrint = new LabReqPrint();
            labReqMain.setBarCode(labHisReq.getBarCodeNo());
            reqNo = labHisReq.getReqNo();
            if (!Objects.equals(reqNo, oldReqNo)) {
                BeanUtil.copyProperties(labHisReq, labReqMain, "id");
                switch (labHisReq.getSex()) {
                    case "男":
                        sex = "1";
                        break;
                    case "女":
                        sex = "2";
                }
                if (!StringUtils.isEmpty(sex)) {
                    labReqMain.setSex(sex);
                }

                labReqMain.setPrinterNa(sysUser.getRealname());
                labReqMain.setOrgId(sysUser.getOrgId());
                labReqMain.setPrintDoctor(sysUser.getUsername());
                Date now = new Date();
                Timestamp ts = new Timestamp(now.getTime());
                labReqMain.setPrintTime(ts);
                labReqMain.setReqNo(reqNo);
                labReqMain.setState("30");
                labReqMain.setStateNa(value);
                //说明是接口调过来的，慎重修改！！！
                if (StrUtil.isNotEmpty(sysUser.getRealname())) {
                    labReqMain.setRemark3("主程序已打印");
                }
                try {
                    if (StringUtils.isNotBlank(labHisReq.getAgeStr())) {
                        AgeUtils ageUtils = new AgeUtils();
                        AgeResultDto ageRes = ageUtils.CalcAge(labHisReq.getAgeStr());
                        labReqMain.setAge(ageRes.getAge());
                        labReqMain.setAgeUnit(ageRes.getAgeUnit());

                    } else {
                        if (BeanUtil.isNotEmpty(labHisReq.getBirthDay())) {
                            AgeUtils ageUtils = new AgeUtils();
                            AgeResultDto ageRes = ageUtils.calcAgeByBirthday(labHisReq.getBirthDay());
                            labReqMain.setAge(ageRes.getAge());
                            labReqMain.setAgeUnit(ageRes.getAgeUnit());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            oldReqNo = reqNo;
            if (!StringUtils.isEmpty(labReqMain.getReqNo())) {
                labReqMainList.add(labReqMain);
            }

            //保存明细信息
            BeanUtil.copyProperties(labHisReq, labReqdetail, "id");

            //判断price是否为空,如果为空通过feecode从labFeeItems中取price
            if (Objects.isNull(labHisReq.getPrice())) {
                for (LabFeeItem labFeeItem : labFeeItems) {
                    if (labHisReq.getFeeCode().equals(labFeeItem.getFeeCode())) {
                        labHisReq.setPrice(labFeeItem.getPrice());
                    }
                }
            }

            BigDecimal costs = new BigDecimal(0);
            try {
                costs = labHisReq.getAmount().multiply(labHisReq.getPrice());
            } catch (Exception e) {
                logger.info("计算价格异常！");
            }
            labReqdetail.setReqNo(reqNo);
            labReqdetail.setHisUnique(labHisReq.getApplicantId());
            labReqdetail.setHisAdvNo(labHisReq.getAdviceId());
            labReqdetail.setOrgId(sysUser.getOrgId());
            labReqdetail.setCosts(costs);
            labReqdetail.setPrice(labHisReq.getPrice());
            labReqDetailList.add(labReqdetail);
            //保存打印记录信息
            labReqPrint.setHisReqId(labHisReq.getId());
            labReqPrint.setApplicationId(labHisReq.getApplicantId());
            labReqPrint.setOrgId(sysUser.getOrgId());
            labReqPrintList.add(labReqPrint);

            // LambdaQueryWrapper<LabHisReq> wrapper = new LambdaQueryWrapper<>();
            // wrapper.eq(LabHisReq::getPatNo, labHisReq.getPatNo()).eq(LabHisReq::getFeeCode, labHisReq.getFeeCode())
            //         .eq(LabHisReq::getAdviceId, labHisReq.getAdviceId());
            // labHisReqMapper.update(labHisReq, wrapper);

        }

        /*计算申请目的*/
        for (LabReqMain m : labReqMainList) {
            if (StringUtils.isEmpty(m.getReqNo())) {
                continue;
            }
            List<LabReqdetail> details = labReqDetailList.stream().filter(p -> p.getReqNo().equals(m.getReqNo())).collect(Collectors.toList());
            if (!details.isEmpty()) {
                String aims = details.stream().map(LabReqdetail::getFeeName).collect(Collectors.joining(","));
                m.setReqPurpose(aims);
            }
        }

        /*条码打印方式
         * 1、LIS 打印条码
         * 2、HIS打印条码
         * 3、启用本地参数中配置
         * 没有配置  默认采用LIS  打印条码处理
         * */
        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("tmdyfs");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        if (!r1.isEmpty()) {
            if (r1.get(0).getValue().equals("2")) {
                //如果是his打印条码的话，没打一次需要把申请表的数据清除
                List<String> collect1 = labReqMainList.stream().map(LabReqMain::getReqNo).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect1)) {
                    LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.in(LabReqMain::getReqNo, collect1).eq(LabReqMain::getDelFlag, 0);
                    labReqMainService.remove(lambdaQueryWrapper);

                    LambdaQueryWrapper<LabReqdetail> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper1.in(LabReqdetail::getReqNo, collect1).eq(LabReqdetail::getDelFlag, 0);
                    labReqdetailService.remove(lambdaQueryWrapper1);
                }
            }
        }

        //SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByXTXXXParam(sysUser.getOrgId(), "mzdytmzdbccysj", "1");//.getValueByKeys(param);


        /*门诊打印条码自动生成采样时间*/
        sysp1 = new SysParamParam();
        sysp1.setParamCode("cyzxxtcs");
        sysp1.setField("mzdytmzdbccysj");
        r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);

        Date utilDate = new Date(); // 当前时间
        Timestamp timestamp = new Timestamp(utilDate.getTime());


        Map<String, LabReqMain> reqNoToMainMap = labReqMainList.stream()
                .collect(Collectors.toMap(LabReqMain::getReqNo, main -> main));

        //收集labReqDetailList里reqNo一样的数据
        Map<String, List<LabReqdetail>> reqNoToDetailListMap = labReqDetailList.stream()
                .collect(Collectors.groupingBy(LabReqdetail::getReqNo));

        // 3. 将明细数据关联到对应的主表对象中
        reqNoToDetailListMap.forEach((reqNo1, detailList) -> {
            // 找到对应的主表对象
            LabReqMain main = reqNoToMainMap.get(reqNo1);

            // 如果主表对象存在，则设置明细数据
            if (main != null) {
                // 这里假设LabReqMain类有setDetails方法
                main.setLabReqdetails(detailList);
            }
        });

        //保存数据到数据库
        for (LabReqMain labReqMain : labReqMainList) {
            if ("1".equals(labReqMain.getPatType())) {

                if (!r1.isEmpty()) {
                    if (r1.get(0).getValue().equals("1")) {
                        labReqMain.setSamplingDoctor(sysUser.getUsername());
                        labReqMain.setSamplingTime(timestamp);
                    }
                }
            }

            try {
                LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabReqMain::getReqNo, labReqMain.getReqNo()).eq(LabReqMain::getDelFlag, 0);
                boolean b = labReqMainService.saveOrUpdate(labReqMain, lambdaQueryWrapper);
                if (!b) {
                    return Result.fail("插入申请主信息报错");
                } else {
                    //插入明细表
                    for (LabReqdetail labReqdetail : labReqMain.getLabReqdetails()) {
                        LambdaQueryWrapper<LabReqdetail> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(LabReqdetail::getReqNo, labReqdetail.getReqNo())
                                .eq(LabReqdetail::getFeeCode, labReqdetail.getFeeCode())
                                .eq(LabReqdetail::getDelFlag, 0);
                        boolean a = labReqdetailService.saveOrUpdate(labReqdetail, queryWrapper);
                        if (!a) {
                            return Result.fail("插入申请明细信息报错");
                        } else {
                            LabHisReq hisReq = new LabHisReq();
                            hisReq.setReqNo(labReqdetail.getReqNo());
                            LambdaQueryWrapper<LabHisReq> wrapper = new LambdaQueryWrapper<>();
                            wrapper.eq(LabHisReq::getPatNo, labReqMain.getPatNo()).eq(LabHisReq::getFeeCode, labReqdetail.getFeeCode())
                                    .eq(LabHisReq::getAdviceId, labReqdetail.getHisAdvNo());
                            labHisReqMapper.update(hisReq, wrapper);
                        }
                    }
                }
            } catch (Exception e) {
                logger.info("保存数据出现异常:"+e.getMessage());
            }

        }

        //labReqPrintService.saveBatch(labReqPrintList);

        // for (LabReqdetail labReqdetail : labReqDetailList) {
        //     LambdaQueryWrapper<LabReqdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //     lambdaQueryWrapper.eq(LabReqdetail::getReqNo, labReqdetail.getReqNo())
        //             .eq(LabReqdetail::getFeeCode, labReqdetail.getFeeCode())
        //             .eq(LabReqdetail::getDelFlag, 0);
        //     boolean b = labReqdetailService.saveOrUpdate(labReqdetail, lambdaQueryWrapper);
        //     if (!b) {
        //         return Result.fail("插入申请明细信息报错");
        //     }
        // }

        // boolean b = labReqMainService.saveBatch(labReqMainList);
        // if (!b) {
        //     return Result.fail("插入申请主信息报错");
        // }
        //
        // boolean b1 = labReqdetailService.saveBatch(labReqDetailList);
        // if (!b1) {
        //     return Result.fail("插入申请明细信息报错");
        // }


        String ids = labReqMainList.isEmpty() ? "" : labReqMainList.stream().map(LabReqMain::getId).collect(Collectors.joining(","));
        //new StringBuilder();
        /*for (LabReqMain labReqMain : labReqMainList) {
            LabReqState labReqState = new LabReqState();
            String id = labReqMain.getId();
            LambdaQueryWrapper<LabReqState> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LabReqState::getDelFlag, 0).eq(LabReqState::getReqMainId, id);
            Integer count = labReqStateMapper.selectCount(wrapper);
            count++;
            ids.append(id).append(",");
            labReqState.setReqMainId(id);
            labReqState.setStateCode("30");
            labReqState.setStateValue(value);
            labReqState.setSeq(Long.valueOf(count));
            labReqState.setOrgId(sysUser.getOrgId());
            labReqState.setRemark(value);
            labReqState.setReqNo(labReqMain.getReqNo());
            labReqStateList.add(labReqState);
        }*/
        /*boolean b3 = labReqStateService.saveBatch(labReqStateList);
        if (!b3) {
            return Result.fail("插入状态记录信息报错");
        }*/

        /*if (ids.length() > 0) {
            //方法一  : substring
            ids = new StringBuilder(ids.substring(0, ids.length() - 1));
        }*/
        //调用打印条码接口
        try {
            String code = "PRINT_BARCODE";
            List<SysInterfaceDict> allSysInterfaceDict = interfaceUtil.getAllSysInterfaceDict(code);
            if (CollectionUtils.isNotEmpty(allSysInterfaceDict)) {
                for (SysInterfaceDict sysInterfaceDict : allSysInterfaceDict) {
                    try {
                        String webUrl = "";
                        if (sysInterfaceDict.getWebUrl().startsWith("http:")) {
                            webUrl = sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                        } else {
                            webUrl = "http://" + sysInterfaceDict.getWebUrl() + "/" + sysInterfaceDict.getCode();
                        }
                        JSONObject jsonObject = new JSONObject();
                        List<String> collect2 = collect.stream().map(LabHisReq::getReqNo).collect(Collectors.toList());
                        jsonObject.set("reqNos", collect2);
                        //操作人
                        jsonObject.set("username", sysUser.getUsername());
                        jsonObject.set("realname", sysUser.getRealname());
                        String returnMsg1 = HttpUtil.createPost(webUrl).body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                        JSONObject reportObject = JSONUtil.parseObj(returnMsg1);
                        logger.info(returnMsg1);
                        JSONObject reportStatus = reportObject.getJSONObject("status");
                        String reportCode = reportStatus.get("code").toString();
                        if ("400".equals(reportCode)) {

                            return Result.fail("接口管理平台异常,请检查");
                        }
                        /*else {
                            //获取userId查询表获取用户信息
                            return Result.succ(1, "退费成功", "");
                        }*/
                    } catch (Exception e) {
                        logger.info("接口方法异常：" + sysInterfaceDict.getType());
                    }
                }
            }
        } catch (Exception e) {
            logger.info("打印条码接口异常，请核实！");
            e.printStackTrace();
        }

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect1 = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        //开始上机医嘱状态更新
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect1)) {
            /*发布报告相关*/
            for (String webUrl : collect1) {
                //调用修改状态接口
                logger.info("开始执行打印条码接口");
                String updateUrl = webUrl + "/lisRestFul/noticeHisFeeByReqNo";
                JSONObject jsonObject = new JSONObject();
                List<String> collect2 = collect.stream().map(LabHisReq::getReqNo).collect(Collectors.toList());
                jsonObject.set("reqNos", collect2);
                //操作人
                jsonObject.set("username", sysUser.getUsername());
                jsonObject.set("realname", sysUser.getRealname());
                jsonObject.set("orgId", sysUser.getOrgId());
                String body = HttpUtil.createPost(updateUrl).body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                logger.info("打印条码接口返回" + body);
            }
        }

        /*标本流程状态记录*/
        SysUser finalSysUser = sysUser;
        String finalValue = value;
        new Thread(() -> {
            List<LabReqState> reqStates = new ArrayList<>();
            for (LabReqMain labReqMain : labReqMainList) {
                LabReqState m = new LabReqState();
                m.setReqMainId(labReqMain.getId());
                m.setSeq(labReqStateService.getMaxCount(labReqMain.getReqNo()));
                m.setStateCode("30");
                m.setReqNo(labReqMain.getReqNo());
                m.setStateValue(finalValue);
                m.setOrgId(labReqMain.getOrgId());
                m.setCreator(finalSysUser.getId());
                String remark = "【" + new Timestamp(System.currentTimeMillis()) + "】,打印条码";
                try {
                    if (!BeanUtil.isEmpty(finalSysUser)) {
                        remark = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + finalSysUser.getRealname() + ",打印条码";
                    } else {
                        remark = "【" + new Timestamp(System.currentTimeMillis()) + "】,打印条码";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                m.setRemark(remark);
                reqStates.add(m);
            }
            labReqStateService.saveBatch(reqStates);
        }).start();

        return Result.succ(1, "条码打印成功", ids);
    }

    @Override
    public Result getPatInfo(PrintBarcodeDto dto) {
        MPJLambdaWrapper<LabHisReq> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabHisReq.class).eq(LabHisReq::getDelFlag, 0);

        String patNo = dto.getPatNo();
        if (!StringUtils.isEmpty(patNo)) {
            queryWrapper.eq(LabHisReq::getPatNo, patNo);
        }
        String reqNo = dto.getReqNo();
        if (!StringUtils.isEmpty(reqNo)) {
            queryWrapper.eq(LabHisReq::getMainId, reqNo);
        }
        String bedNo = dto.getBedNo();
        if (!StringUtils.isEmpty(bedNo)) {
            queryWrapper.eq(LabHisReq::getBedNo, bedNo);
        }
//        String patType = dto.getPatType();
        if (ToolsUtils.isNotEmpty(dto.getPatType()) && dto.getPatType().size() > 0) {
            queryWrapper.in(LabHisReq::getPatType, dto.getPatType());
        }
        List<String> deptList = dto.getDeptNo();
        if (deptList.size() > 0) {
            queryWrapper.in(LabHisReq::getReqDept, deptList);
        }

        String patNa = dto.getPatNa();
        if (!StringUtils.isEmpty(patNa)) {
            queryWrapper.eq(LabHisReq::getPatNa, patNa);
        }

        String idNo = dto.getIDNo();
        if (!StringUtils.isEmpty(idNo)) {
            queryWrapper.eq(LabHisReq::getIdNo, idNo);
        }
        // queryWrapper
        //         .ge(LabHisReq::getReqTime, dto.getReqDateS())
        //         .le(LabHisReq::getReqTime, dto.getReqDateE());
        queryWrapper.between(LabHisReq::getReqTime, dto.getReqDateS(), dto.getReqDateE());
        String searchValue = dto.getSearchValue();
        if (ToolsUtils.isNotEmpty(searchValue)) {
            queryWrapper.and(p -> p.like(LabHisReq::getPatNa, searchValue).or().like(LabHisReq::getPatNo, searchValue).or().like(LabHisReq::getBedNo, searchValue).or().like(LabHisReq::getReqNo, searchValue));
        }
        StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_REQ_PRINT p WHERE t.ID = p.HIS_REQ_ID ");
        queryWrapper.notExists(existsSql.toString());

        List<LabHisReq> labHisReqList = labHisReqMapper.selectList(queryWrapper);

        return Result.succ(1, "查询成功", labHisReqList);
    }

    //预制条码
    @Override
    public Result prefabricateBarcode(PrintBarcodeDto dto) {
        MPJLambdaWrapper<LabHisReq> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabHisReq.class).eq(LabHisReq::getDelFlag, 0);

        String patNo = dto.getPatNo();
        if (!StringUtils.isEmpty(patNo)) {
            queryWrapper.eq(LabHisReq::getPatNo, patNo);
        }
        String reqNo = dto.getReqNo();
        if (!StringUtils.isEmpty(reqNo)) {
            queryWrapper.eq(LabHisReq::getMainId, reqNo);
        }
        String bedNo = dto.getBedNo();
        if (!StringUtils.isEmpty(bedNo)) {
            queryWrapper.eq(LabHisReq::getBedNo, bedNo);
        }
        if (ToolsUtils.isNotEmpty(dto.getPatType()) && dto.getPatType().size() > 0) {
            queryWrapper.eq(LabHisReq::getPatType, dto.getPatType());
        }
        List<String> deptList = dto.getDeptNo();
        if (deptList.size() > 0) {
            queryWrapper.in(LabHisReq::getReqDept, deptList);
        }

        String patNa = dto.getPatNa();
        if (!StringUtils.isEmpty(patNa)) {
            queryWrapper.eq(LabHisReq::getPatNa, patNa);
        }

        String idNo = dto.getIDNo();
        if (!StringUtils.isEmpty(idNo)) {
            queryWrapper.eq(LabHisReq::getIdNo, idNo);
        }
        // queryWrapper
        //         .ge(LabHisReq::getReqTime, dto.getReqDateS())
        //         .le(LabHisReq::getReqTime, dto.getReqDateE());
        queryWrapper.between(LabHisReq::getReqTime, dto.getReqDateS(), dto.getReqDateE());

        StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_REQ_PRINT p WHERE t.ID = p.HIS_REQ_ID ");
        queryWrapper.notExists(existsSql.toString());

        List<LabHisReq> labHisReqList = labHisReqMapper.selectList(queryWrapper);


        //根据病历号和项目排序
        List<LabHisReq> collect = labHisReqList.stream().sorted(Comparator.comparing(LabHisReq::getPatNo, Comparator.reverseOrder()).thenComparing(LabHisReq::getFeeCode, Comparator.reverseOrder())).collect(Collectors.toList());


        String oldPatNo = null, oldBarcodeType = null, oldFeeCode = null, oldMainId = null, color = null;

        //循环判断是否需要分管
        for (LabHisReq labHisReq : collect) {

            //是否分管标识
            boolean newReq = false;
            //判断是否是同一病人，如果不是则分管
            patNo = labHisReq.getPatNo();
            if (!Objects.equals(oldPatNo, patNo)) {
                newReq = true;
            }
            oldPatNo = patNo;

            //判断分管类别，如果不是同一类别则分管
            String feeCode = labHisReq.getFeeCode();
            LambdaQueryWrapper<LabFeeItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LabFeeItem::getDelFlag, 0).eq(LabFeeItem::getFeeCode, feeCode);
            LabFeeItem labFeeItem = labFeeItemMapper.selectOne(wrapper);

            LabFeeitemVsBarcode labFeeitemVsBarcode = new LabFeeitemVsBarcode();
            if (BeanUtil.isEmpty(labFeeItem)) {
                labHisReq.setCatchMessage("查无申请项目");
            } else {
                LambdaQueryWrapper<LabFeeitemVsBarcode> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(LabFeeitemVsBarcode::getDelFlag, 0)
                //.eq(LabFeeitemVsBarcode::getFeeId, labFeeItem.getId())
                ;
                labFeeitemVsBarcode = labFeeitemVsBarcodeMapper.selectOne(queryWrapper1);
            }

//            String barcodeId = StringUtils.isEmpty(labFeeitemVsBarcode.getBarcodeId()) ? "" : labFeeitemVsBarcode.getBarcodeId();
//
//            if (StringUtils.isEmpty(barcodeId)) {
//                labHisReq.setCatchMessage(labHisReq.getCatchMessage() + "," + "申请项目标本类型无对照");
//            }
//
//            if (!Objects.equals(barcodeId, oldBarcodeType)) {
//                newReq = true;
//            }
//            oldBarcodeType = barcodeId;

            //申请项目相同
            if (Objects.equals(feeCode, oldFeeCode)) {
                newReq = true;
            }
            oldFeeCode = feeCode;

            //判断是否分管
            if (newReq) {
                //生成随机的颜色值,同一条码颜色一样
                StringBuffer result = new StringBuffer();
                for (int i = 0; i < 6; i++) {
                    //随机生成0-15的数值并转换成16进制
                    result.append(Integer.toHexString(new Random().nextInt(16)));
                }
                color = "#" + result.toString().toUpperCase();
            }
            labHisReq.setReqNo(reqNo);
            labHisReq.setSameSpecCodeBgColor(color);
        }

        return Result.succ(1, "成功", labHisReqList);

    }

    @Override
    public Result getIdCardByBarcode(String barcode) {

        String type;
        if (barcode.length() == 28) {
            type = "1";
        } else if (barcode.length() >= 64) {
            type = "2";
        } else {
            return Result.succ(1, "成功", barcode);
        }

        /*先调接口拉取数据*/
        LambdaQueryWrapper<SysInterface> interwrapper = new LambdaQueryWrapper<>();
        interwrapper.eq(SysInterface::getDelFlag, 0);
        interwrapper.eq(SysInterface::getIsEnable, 1);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(interwrapper);
        List<String> collect2 = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        try {
            if (CollectionUtils.isNotEmpty(collect2)) {
                for (String webUrl : collect2) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.set("barcode", barcode);

                    String returnMsg = null;
                    if ("1".equals(type)) {
                        //电子医保凭证
                        returnMsg = HttpUtil.createPost(webUrl + "/getIdNoByMedicalQRCode").body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                    } else if ("2".equals(type)) {
                        //截取barcode保留前64位
                        barcode = barcode.substring(0, 64);
                        //电子健康卡
                        LabReqMain q = new LabReqMain();
                        q.setReqNo(barcode);

                        returnMsg = HttpUtil.createPost(webUrl + "/getIdNoByHealthCard").body(JSONUtil.toJsonStr(q)).contentType("application/json").execute().body();
                    }

                    JSONObject jsonObject1 = JSONUtil.parseObj(returnMsg);
                    JSONObject status = jsonObject1.getJSONObject("status");
                    String code = status.get("code").toString();
                    String data = jsonObject1.getStr("data");
                    logger.info("调用接口返回:" + code);
                    if ("400".equals(code)) {
                        String msg = status.get("msg").toString();
                        return Result.fail(msg);
                    } else {
                        return Result.succ(1, "成功", data);
                    }
                }
            }
        } catch (Exception e) {
            //throw new RuntimeException("接口管理平台异常,请检查");
        }

        return Result.fail("接口管理平台异常,请检查");

    }


}
